package com.zhenai.rocyuan.modules.threadupdown.client;

import java.io.File;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.UnknownHostException;

import org.apache.log4j.Logger;

import com.zhenai.rocyuan.modules.threadupdown.BaseSocket;
import com.zhenai.rocyuan.modules.threadupdown.BaseSocketTool;
import com.zhenai.rocyuan.modules.threadupdown.HandleType;
import com.zhenai.rocyuan.modules.threadupdown.Operation;
import com.zhenai.rocyuan.modules.threadupdown.Users;

public class ClientAction {
	private ClientSocket cs = null;
	private String ip = BaseSocket.SERVER_HOSE;
	private int port = BaseSocket.SERVER_PORT;
	private Users user;
	private String file;
	private static final Logger log = Logger.getLogger(ClientAction.class);

	/**
	 * 客户端启动入口
	 * 
	 * @param user
	 *            用户信息
	 */
	public ClientAction(Users user) {
		this.user = user;
	}

	/**
	 * 客户端与服务器通讯入口 <br>
	 * 注意：客户端可以根据最后返回的参数，来进行下一步操作，以保证本次需要从服务器下载的文件得以成功下载<br>
	 * 0: User is null<br>
	 * 1: 连接服务器失败<br>
	 * 2: User 验证失败[用户名或密码有误]<br>
	 * 3: 操作成功<br>
	 * 4: 操作失败<br>
	 * 5: 服务器端未找到相关Class<br>
	 * 6: 与服务器连接过程中出现传输异常<br>
	 * 7:Operation is null<br>
	 * 
	 * @return
	 */
	public Operation work(Operation operation) {
		int returnFlag = HandleType.RETURN_USER_OR_OPERATION_NULL;
		Operation opera = new Operation(returnFlag, null);
		if (user == null || operation == null) {
			return opera;
		}
		ObjectOutputStream out = null;
		ObjectInputStream in = null;
		try {
			if (createConn()) {
				in = cs.getIn();
				out = cs.getOut();
				// 先检查服务器端发送过来的首次验证
				boolean flag = in.readBoolean();
				if (!flag) {
					returnFlag = HandleType.RETURN_IP_LIMIT;
				} else {
					BaseSocketTool tool = new BaseSocketTool();
					// 发送 User 到服务器验证
					tool.writeObject(out, user);
					// this.cs.sendObject(user, out);
					// out.flush();
					// 获取服务器验证返回的数据,根据返回的数据来判断是否进行下一步操作
					boolean validateFlag = tool.readBoolean(in);
					if (validateFlag) {
						tool.writeObject(out, operation);
						try {
							if (operation.getType() == HandleType.FILE_DOWNLOAD) {
								tool.readFile(operation.getObj().toString(), out, in, true);
							} else if (operation.getType() == HandleType.FILE_UPLOAD) {
								file = operation.getObj().toString();
								File uploadFile = new File(file);
								if (uploadFile.exists() && uploadFile.isFile()) {
									tool.writeFile(out, in, uploadFile);
								}
							}
							log.error("客户端最后读对象" + Thread.currentThread().getName());
							opera = (Operation) tool.readObject(in);
							returnFlag = opera.getType();
						} catch (ClassNotFoundException e) {
							e.printStackTrace();
						}
					} else {
						returnFlag = HandleType.RETURN_USER_VALIDATE_FAIL;
						log.debug("---客户端[User]验证失败，服务器拒绝本客戶端继续连接");
					}
				}
			} else {
				returnFlag = HandleType.RETURN_CONNECT_FAIL;
			}
		} catch (IOException ex) {
			log.error(ex, ex);
			returnFlag = HandleType.RETURN_CONNECT_EXCEPTION;
		} finally {
			this.cs.closeConnect();
		}
		opera.setType(returnFlag);
		return opera;
	}

	/**
	 * 建立与服务器端的连接
	 * 
	 * @return
	 */
	private boolean createConn() {
		cs = new ClientSocket(ip, port);
		try {
			cs.getConnect();
			return true;
		} catch (UnknownHostException e) {
			log.error(e, e);
			return false;
		} catch (Exception e) {
			log.debug("----连接服务器失败-----");
			log.error(e, e);
			return false;
		}
	}

	/**
	 * 断开连接
	 */
	public void tearDownConnection() {
		if (cs != null) {
			cs.closeConnect();
		}
	}

	public String getFile() {
		return file;
	}

	public void setFile(String file) {
		this.file = file;
	}

	public static void main(String arg[]) {
		if (arg == null) {
			return;
		}
		int size = Integer.parseInt(arg[0]);
		for (int i = 0; i < size; i++) {
			log.error("^^^^^^^" + i + "^^^^^^");
			Users user = new Users();
			user.setUserName("admin");
			final ClientAction client = new ClientAction(user);
			final Operation ooo = new Operation();
			// Users u = new Users();
			// u.setUserName("yhs-adm" + BaseSocket.c);
			// u.setIsEffective(1);
			// u.setPhone("13041125508");
			// u.setrId(13);
			// Log log = new Log();
			// log.setOperationContent("用户请求连接服务器一次" + i);
			// log.setOperationTime(new Date());
			// log.setOperationType(1);
			// // log.setUser(user);
			// log.setUserId(1);
			//
			// List<Integer> list = new ArrayList<Integer>();
			// list.add(10);
			// list.add(100);
			// list.add(200);
			if (arg.length > 1) {
				ooo.setType(HandleType.FILE_UPLOAD);
				ooo.setObj("E:/111/s.mp4");
				System.out.println("***** 上  传  ******");
			} else {
				ooo.setType(HandleType.FILE_DOWNLOAD);
				ooo.setObj("E:/zzz");
				System.out.println("***** 下  载  ******");
			}

			new Thread(new Runnable() {
				@Override
				public void run() {
					Operation onew = client.work(ooo);
					System.out.println("-----++++++++--------" + onew);
				}
			}).start();
		}
	}
}